#ifndef _THREAD_HPP__
#define _THREAD_HPP__
#include <iostream>
#include <string>
#include <functional>
#include <pthread.h>
#include <sys/types.h>
#include <unistd.h>
#include <cstdio>
using namespace std;

namespace MyThread
{
    template <typename T>
    using func_t = function<void(T &)>;

    static int number = 1;
    enum TSTATUS
    {
        NEW,
        RUNNING,
        STOP
    };
    template <typename T>
    class Thread
    {
    private:
        // 成员方法！ void* Routinue(Thread* this,void* args)
        static void *Routinue(void *args)
        {
            Thread<T> *t = (Thread<T> *)args;
            t->_status = TSTATUS::RUNNING;
            t->_func(t->_data);
            return nullptr;
        }

        void EnableDetach()
        {
            _joinable = false;
        }

    public:

        Thread(func_t<T> func, T &data = 0) : _func(func), _status(TSTATUS::NEW), _joinable(true), _data(data)
        {
            _name = "Thread-" + to_string(number++);
            _pid = getpid();
        }
        // 创建
        bool Start()
        {
            if (_status != TSTATUS::RUNNING)
            {
                int n = ::pthread_create(&_tid, nullptr, Routinue, this);
                if (n != 0)
                    return false;
                return true;
            }
            return false;
        }
        // 停止
        bool Stop()
        {
            if (_status == TSTATUS::RUNNING)
            {
                int n = ::pthread_cancel(_tid);
                if (n != 0)
                    return false;
                return true;
            }
            return false;
        }
        // 等待
        bool Join()
        {
            if (_joinable)
            {
                int n = ::pthread_join(_tid, nullptr);
                if (n != 0)
                    return false;
                _status = TSTATUS::STOP;
                return true;
            }
            return false;
        }
        // 分离
        void Detach()
        {
            EnableDetach();
            pthread_detach(_tid);
        }

        bool IsJoinable() { return _joinable; }

        string Name() { return _name; }
        ~Thread()
        {
        }

    private:
        string _name;
        pthread_t _tid;
        pid_t _pid;
        bool _joinable; // 是否分离，默认不是
        func_t<T> _func;
        TSTATUS _status;
        T &_data;
    };

}

#endif